package com.nanako.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanako.common.R;
import com.nanako.entity.Category;
import com.nanako.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 新增分类
     */
    @PostMapping
    public R saveCategory(@RequestBody Category category) {
        redisTemplate.delete("category");
        if (categoryService.save(category)) {
            return R.success("添加成功☆*: .｡. o(≧▽≦)o .｡.:*☆");
        }
        return R.error("添加失败≡(▔﹏▔)≡");
    }

    /**
     * 分类分页查询
     *
     * @param page     当前页码
     * @param pageSize 当前条数
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize) {
        IPage<Category> pageInfo = new Page<>(page, pageSize);
        categoryService.page(pageInfo);
        return R.success(pageInfo);
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    public R deleteCategory(Long id) {
        redisTemplate.delete("category");
        if (categoryService.cascadingDeleteCheck(id) &&
                categoryService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    /**
     * 修改分类
     */
    @PutMapping
    public R updateCategory(@RequestBody Category category) {
        redisTemplate.delete("category");
        if (categoryService.updateById(category)) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 查询菜品分类
     *
     * @param type
     * @return
     */
    @GetMapping("/list")
    public R queryList(String type) {
        Object category = redisTemplate.opsForValue().get("category");
        if (ObjectUtils.isNotEmpty(category)) {
            return R.success(category);
        }
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(type), Category::getType, type)
                .orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(wrapper);
        redisTemplate.opsForValue().set("category", list);
        return R.success(list);
    }

}
